package com.thx.appserver.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.thx.appserver.model.CappNews;
import com.thx.common.struts2.CurdAction;


/**
 *
 * @author HP
 * @version 2.1
 *
 */
@ParentPackage(value = "gloab-package")
@Namespace(value = "/")
@Action(value = "fileUpDown", interceptorRefs = {
		@InterceptorRef(value = "pageInterceptor"),
		@InterceptorRef(value = "token", params = { "includeMethods", "save" }),
		@InterceptorRef("topDtStack") })
@Controller
@Scope("prototype")
public class FileUpDownAction extends CurdAction<CappNews> {
    /**
	 *
	 */
	private static final long serialVersionUID = -7669086738580137666L;
	private File imgFile;
    /**
     * 文件名称
     */
    private String imgFileFileName;

    /**
     * 图片宽度
     */
    private String imgWidth;

    /**
     * 图片高度
     */
    private String imgHeight;

    /**
     * 图片对齐方式
     */
    private String align;

    /**
     * 图片标题
     */
    private String imgTitle;

	public File getImgFile() {
		return imgFile;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public String getImgFileFileName() {
		return imgFileFileName;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	public String getImgWidth() {
		return imgWidth;
	}

	public void setImgWidth(String imgWidth) {
		this.imgWidth = imgWidth;
	}

	public String getImgHeight() {
		return imgHeight;
	}

	public void setImgHeight(String imgHeight) {
		this.imgHeight = imgHeight;
	}

	public String getAlign() {
		return align;
	}

	public void setAlign(String align) {
		this.align = align;
	}

	public String getImgTitle() {
		return imgTitle;
	}

	public void setImgTitle(String imgTitle) {
		this.imgTitle = imgTitle;
	}
	public String uploadImg() {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
        response.setContentType("text/html; charset=UTF-8");
        // 文件保存目录路径
        String savePath = ServletActionContext.getServletContext().getRealPath("/") + "attached/";
        // 文件保存目录URL
        String saveUrl = request.getContextPath() + "/attached/";
        // 定义允许上传的文件扩展名
        String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
        // 最大文件大小
        long maxSize = 2*1024*1024;
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e1) {
        	logger.error(e1.getMessage(),e1);
        }

        if (imgFile == null) {
            out.println(getError("请选择文件。"));
            return null;
        }

        // 检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
        	uploadDir.mkdir();
            return null;
        }
        // 检查目录写权限
        if (!uploadDir.canWrite()) {
            out.println(getError("上传目录没有写权限。"));
            return null;
        }
        // 创建文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        String year = ymd.substring(0, 4);
		String mon = ymd.substring(4,6);
		String day = ymd.substring(6, 8);
        savePath += year + "/"+mon + "/"+day + "/";
        saveUrl += year + "/"+mon + "/"+day + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String fileExt = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String> asList(fileTypes).contains(fileExt)) {
            out.println(getError("上传文件扩展名[" + fileExt + "]是不允许的扩展名。"));
            return null;
        }
        if (imgFile.length() > maxSize) {
            out.println(getError("[ " + imgFileFileName + " ]超过单个文件大小限制，文件大小[ " + imgFile.length() + " ]，限制为[ " + maxSize + " ] "));
            return null;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = new File(savePath, newFileName);
        try {
            FileUtils.copyFile(imgFile, uploadedFile);
            JSONObject obj = new JSONObject();
            obj.put("error", 0);
            obj.put("url", saveUrl + newFileName);
            out.println(obj.toString());
        } catch (Exception e) {
        	logger.error(e.getMessage(),e);
        }
        return null;
    }
    private String getError(String message) {
        JSONObject obj = new JSONObject();
        try {
			obj.put("error", 1);
			obj.put("message", message);
		} catch (JSONException e) {
			logger.error(e.getMessage(),e);
		}
        return obj.toString();
    }
}
